
import { isRef, onMounted, onUnmounted ,type Ref, unref,watch, ref} from "vue"

export const useAddThing = (
  // 可以接受响应式对象
  target: Ref<EventTarget | null> | EventTarget,
  event:string,
  handleFn:(e:Event)=>void
)=>{
  // 判断是否为响应式对象
  const refTarget = isRef(target) ? target : ref(target) as Ref<EventTarget | null>
  
  // 响应式对象用监听，不用 onMounted 了
  watch(refTarget,(newValue,oldValue)=>{
    oldValue?.removeEventListener(event,handleFn)
    newValue?.addEventListener(event,handleFn)
  },{
    // 初始值也监听
    immediate:true
  })
  
  onUnmounted(()=>{
    // 脱去 ref 的衣服，如果有的话
    // 停止监听并移除事件
    refTarget.value?.removeEventListener(event,handleFn)
  })
}